package com.redis.springtest.jedis_test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-12-16 下午1:29
 */
public class TestTx2 {
    public static void main(String[] args) {
        transMethod();
    }

    public static boolean transMethod() {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        int balance;//可用余额
        int debt;//欠额
        int amtToSubtract = 10;//实际扣减额度

        jedis.watch("balance");
        balance = Integer.parseInt(jedis.get("balance"));
        if (balance < amtToSubtract) {
            jedis.unwatch();
            System.out.println("modify");
            return false;
        } else {
            System.out.println("-------------transaction");
            Transaction transaction = jedis.multi();
            transaction.decrBy("balance", amtToSubtract);
            transaction.incrBy("debt", amtToSubtract);
            transaction.exec();

            balance = Integer.parseInt(jedis.get("balance"));
            debt = Integer.parseInt(jedis.get("debt"));

            System.out.println("**********" + balance);
            System.out.println("**********" + debt);

            return true;
        }
    }
}
